package com.sf.fy.uav.applet.scenicspot;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.sf.fy.uav.common.awt.RepeatSubmit;
import com.sf.fy.uav.common.request.common.IdRequest;
import com.sf.fy.uav.common.request.operate.OrderInfoReq;
import com.sf.fy.uav.common.response.operational.OrderInfoRes;
import com.sf.fy.uav.common.response.order.task.ScenicSpotOrderDetailRes;
import com.sf.fy.uav.common.utils.RespJsonPageData;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.order.controller.OrderInfoRest;
import com.sf.fy.uav.order.service.impl.OrderInfoServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ta136817
 */
@RestController
@RequestMapping("/home/orderInfo/")
@RequiredArgsConstructor
@Tag(name = "订单管理", description = "订单管理")
@Api(tags = "订单管理")
public class OrderInfoController {
    private final static Logger logger = LoggerFactory.getLogger(OrderInfoController.class);

    private final OrderInfoRest orderInfoRest;

    private final OrderInfoServiceImpl iOrderInfoService;

    @GetMapping("get-order-info")
    @CrossOrigin
    @Operation(tags = "查询订单", description = "查询订单")
    public RespJsonPageData<OrderInfoRes> getScenicSpot(@RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String tcWayBillNo, @RequestParam(required = false) String scenicSpotId, @RequestParam(required = false) String businessId, @RequestParam(required = false) Integer orderStatus,@RequestParam(required = false) String orderStartDate,@RequestParam(required = false) String orderEndDate) {
        OrderInfoReq orderInfoReq = new OrderInfoReq();
        orderInfoReq.setPage(page);
        orderInfoReq.setSize(size);
        orderInfoReq.setScenicSpotId(scenicSpotId);
        orderInfoReq.setTcWayBillNo(tcWayBillNo);
        orderInfoReq.setBusinessId(businessId);
        orderInfoReq.setOrderStatus(orderStatus);
        orderInfoReq.setOrderStartDate(orderStartDate);
        orderInfoReq.setOrderEndDate(orderEndDate);
        return orderInfoRest.getScenicSpotOrder(orderInfoReq);
    }

    @GetMapping("get-order-detail")
    @ApiOperation(value = "获取景区订单详情", notes = "获取景区订单详情")
    public Rs<ScenicSpotOrderDetailRes> getCommodityDetail(@RequestParam String tcWaybillNo) {
        return Rs.success(orderInfoRest.getScenicSpotOrderDetail(tcWaybillNo));
    }
    @GetMapping("export")
    @ApiOperation(value = "导出", notes = "/export")
    @CrossOrigin
    public void export(HttpServletResponse response, @RequestParam Integer page, @RequestParam Integer size, @RequestParam(required = false) String tcWayBillNo, @RequestParam(required = false) String scenicSpotId, @RequestParam(required = false) String businessId, @RequestParam(required = false) Integer orderStatus,@RequestParam(required = false) String orderStartDate,@RequestParam(required = false) String orderEndDate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            response.setHeader("content-Type", "application/vnd.ms-excel");
            String fileName  =  "景区订单明细表" + sdf.format(new Date());
            response.setHeader("content-disposition",
                    "attachment;filename=" +URLEncoder.encode(fileName, StandardCharsets.UTF_8)+ ".xls");
            ExportParams exportParams = new ExportParams();
            RespJsonPageData<OrderInfoRes> orderInfoPage = this.getScenicSpot(page, size, tcWayBillNo, scenicSpotId, businessId, orderStatus,orderStartDate,orderEndDate);
            for (OrderInfoRes orderInfoRes: orderInfoPage.getResponseData()) {
                if(ObjectUtils.allNotNull(orderInfoRes.getPricePaid())&&orderInfoRes.getPricePaid().compareTo(BigDecimal.ZERO)>0){
                    orderInfoRes.setPricePaid(orderInfoRes.getPricePaid().setScale(2, RoundingMode.UP));
                }
                if(!CollectionUtils.isEmpty(orderInfoRes.getCommodityList())){
                    orderInfoRes.getCommodityList().forEach(commodityQuery->{
                        if(ObjectUtils.allNotNull(commodityQuery.getBuyPrice())&&commodityQuery.getBuyPrice().compareTo(BigDecimal.ZERO)>0){
                            commodityQuery.setBuyPrice(commodityQuery.getBuyPrice().setScale(2, RoundingMode.UP));
                        }
                    });
                }
            }
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, OrderInfoRes.class, orderInfoPage.getResponseData());
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
    @PostMapping("cancel-order")
    @RepeatSubmit(interval = 2000, message = "重复提交")
    @ApiOperation(value = "取消订单")
    public Rs<Date> cancelOrder(@RequestBody @Valid IdRequest idRequest) {
        return Rs.success(iOrderInfoService.cancelOrder(idRequest.getId()));
    }
}
